package com.example.spingbootvue.Common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.spingbootvue.entity.User;
import com.example.spingbootvue.exception.ServiceException;
import com.example.spingbootvue.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }

        String token = request.getHeader("token");

        if(handler instanceof HandlerMethod){
            AuthAccess annotation= ((HandlerMethod)handler).getMethodAnnotation(AuthAccess.class);
            if(annotation != null){
                return true;
            }
        }

        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }

        if(StrUtil.isBlank(token)){
            throw new ServiceException("401","Please log in！");
        }
        String id;
        try {
            id= JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new ServiceException("401","Please log in！");
        }
        //根据token中的id查询数据库
        User user=userMapper.selectById(Integer.valueOf(id));
        if(user == null){
            throw new ServiceException("401","Please log in！");
        }
        //通过用户密码加密后 生成一个验证器
        JWTVerifier jwtVerifier= JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            jwtVerifier.verify(token); //验证token
        }catch (JWTVerificationException e){
            throw new ServiceException("401","Please log in！");
        }
        return  true;
    }
}
